package com.example.lcode.binary;

import java.math.BigDecimal;

public class Question400 {

    public int findNthDigit(int n) {
        int base = 9;
        int numLen = 0;
        BigDecimal length = BigDecimal.ZERO;
        int lastLength = 0;
        while (BigDecimal.valueOf(n).compareTo(length) > 0) {
            numLen ++;
            Double v = base * Math.pow(10, numLen - 1);
            int countNumLen = v.intValue();
            lastLength = length.intValue();
            length = length.add(BigDecimal.valueOf(numLen * countNumLen));
        }
        int indexOfNumber = (n - lastLength) % numLen == 0 ? numLen - 1 : (n - lastLength) % numLen - 1;
        Double v = base * Math.pow(10, numLen - 2);
        int isNext = indexOfNumber == numLen - 1 ? 0 : 1;
        int number = ((n - lastLength) / numLen == 0 ? 1 : (n - lastLength) / numLen) + v.intValue() + isNext;
        int result = Integer.valueOf(String.valueOf(number).charAt(indexOfNumber) - '0');
        return result;
    }

//    1,2,3,4,5,6,7,8,9,   9 * 1
//    10,11,12,13,14,15,16,17,18,19 20
//    20
//    30
//    40
//    50
//    60
//    70
//    80
//    90                           90 * 2
//    100
//    110
//    ...
//    200
//    ...
//    ...
//    990                             900 * 3
//    1000
//
//     9990                           9000 * 4
    public static void main(String[] args) {
        Question400 question400 = new Question400();
        int nthDigit = question400.findNthDigit(1000000000);
        System.out.println(nthDigit);
    }

}
